package com.lexiang.user.controller;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import com.lexiang.user.pojo.User;
import com.lexiang.user.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制器层
 * @author Administrator
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private JwtUtil jwtUtil;

	@Autowired
	private HttpServletRequest request;

	private RedisTemplate redisTemplate; //处理乱码

	@Autowired(required = false)
	public void setRedisTemplate(RedisTemplate redisTemplate) {
		RedisSerializer stringSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(stringSerializer);
		redisTemplate.setValueSerializer(stringSerializer);
		redisTemplate.setHashKeySerializer(stringSerializer);
		redisTemplate.setHashValueSerializer(stringSerializer);
		this.redisTemplate = redisTemplate;
	}

	/**
	 * 更新好友粉丝数和用户关注数
	 *
	 * @return
	 */
	@RequestMapping(value = "/{userid}/{friendid}/{x}",method = RequestMethod.PUT)
	public void updatefanscountandfollowcount(@PathVariable String userid,
											  @PathVariable  String friendid,
											  @PathVariable int x){
		userService.updatefanscountandfollowcount(x,userid,friendid);
	}

	//用户的登录
	@RequestMapping(value = "/login",method = RequestMethod.POST)
	public Result login(@RequestBody User user){
		user = userService.login(user.getMobile(),user.getPassword());
		if(user==null){
			return new Result(false,StatusCode.LOGINERROR,"登录失败");
		}
		//具体的登录成功后逻辑：登录成功后，添加token信息
		String token = jwtUtil.createJWT(user.getId(), user.getMobile(), "user");
		Map<String,Object> map = new HashMap<>();
		map.put("token",token);
		map.put("roles","user");
		return new Result(true,StatusCode.OK,"登录成功",map);
	}

	//发送短信验证码
	@RequestMapping(value = "/sendsms/{mobile}",method = RequestMethod.POST)
	public Result sendSms(@PathVariable String mobile){
		userService.sendSms(mobile);
		return new Result(true,StatusCode.OK,"短信发送成功");
	}

	//用户注册
	@RequestMapping(value = "/register/{code}",method = RequestMethod.POST)
	public Result RegisterUser(@PathVariable String code, @RequestBody User user){
		//验证用户短信，利用缓存和用户输入的比较,手机号的获取通过请求封装的对象获取

		String codeRedis = (String) redisTemplate.opsForValue().get("checkcode_"+user.getMobile());


		if(codeRedis.isEmpty()){
			return new Result(false,StatusCode.ERROR,"请先获取手机验证码！");
		}
		if(!codeRedis.equals(code)){
			return new Result(false,StatusCode.ERROR,"请输入正确的验证码！");
		}
		userService.add(user);
		return new Result(true,StatusCode.OK,"注册用户成功！");
	}
	/**
	 * 查询全部数据
	 * @return
	 */
	@RequestMapping(method= RequestMethod.GET)
	public Result findAll(){
		return new Result(true,StatusCode.OK,"查询成功",userService.findAll());
	}
	
	/**
	 * 根据ID查询
	 * @param id ID
	 * @return
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.GET)
	public Result findById(@PathVariable String id){
		return new Result(true,StatusCode.OK,"查询成功",userService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
		Page<User> pageList = userService.findSearch(searchMap, page, size);
		return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<User>(pageList.getTotalElements(), pageList.getContent()) );
	}

	/**
     * 根据条件查询
     * @param searchMap
     * @return
     */
    @RequestMapping(value="/search",method = RequestMethod.POST)
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(true,StatusCode.OK,"查询成功",userService.findSearch(searchMap));
    }
	
	/**
	 * 增加
	 * @param user
	 */
	@RequestMapping(method=RequestMethod.POST)
	public Result add(@RequestBody User user  ){
		userService.add(user);
		return new Result(true,StatusCode.OK,"增加成功");
	}
	
	/**
	 * 修改
	 * @param user
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.PUT)
	public Result update(@RequestBody User user, @PathVariable String id ){
		user.setId(id);
		userService.update(user);		
		return new Result(true,StatusCode.OK,"修改成功");
	}
	
	/**
	 * 删除，必须有admin的权限
	 * @param id
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.DELETE)
	public Result delete(@PathVariable String id ){
		/*String header = request.getHeader("Authorization");
		if(header==null||"".equals(header)){
			return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		}
		//格式不合法
		if(!header.startsWith("LinChong ")){   //Token的格式约定
			return new Result(false,StatusCode.ACCESSERROR,"格式不合法");
		}
		//获得token
		String token = header.substring(9);
		//解析验证token
		try{
			Claims claims = jwtUtil.parseJWT(token);
			String roles = (String) claims.get("roles");
			if(roles==null||!roles.equals("admin")){
				return new Result(false,StatusCode.ACCESSERROR,"权限不足");
			}
		}catch (Exception e){
			return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		}
		try{
			userService.deleteById(id);
			return new Result(true,StatusCode.OK,"删除成功");
		}catch (Exception e){
			return new Result(false,StatusCode.ERROR,"要删除的用户不存在！");
		}*/
		String token = (String) request.getAttribute("claims_admin");
		if(token==null||"".equals(token)){
			return new Result(false,StatusCode.ACCESSERROR,"权限不足！！");
		}
		try {
			userService.deleteById(id);
			return new Result(true, StatusCode.OK,"删除用户成功！");
		}catch (Exception e){
			return new Result(false,StatusCode.ERROR,"用户不存在，删除用户失败!");
		}

	}
	
}
